package com.wss.lsl.mongo.demo;

import java.net.UnknownHostException;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.mongodb.core.MongoOperations;

import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.wss.lsl.mongo.demo.config.SpringMongoConfig;
import com.wss.lsl.mongo.demo.config.SpringMongoConfig3;
import com.wss.lsl.mongo.demo.model.User;

/**
 * Hello world!
 * 
 */
public class App8 {

	public static void main(String[] args) throws UnknownHostException {

		ApplicationContext context = new AnnotationConfigApplicationContext(
				SpringMongoConfig.class);
		MongoOperations operations = context.getBean("mongoTemplate",
				MongoOperations.class);

		User user = new User("wss", "123456");

		// save
		operations.save(user);
		System.out.println("1. user: " + user);

		DBCollection collection = operations.getCollection(operations
				.getCollectionName(User.class));
		DBCursor cursor = collection.find();
		while (cursor.hasNext()) {
			System.out.println(cursor.next());
		}

		// drop collection
		operations.dropCollection(User.class);

		/**
		 * remove _filed class
		 */
		context = new AnnotationConfigApplicationContext(
				SpringMongoConfig3.class);
		operations = context.getBean("mongoTemplate", MongoOperations.class);

		user = new User("wss", "123456");

		// save
		operations.save(user);
		System.out.println("1. user: " + user);

		collection = operations.getCollection(operations
				.getCollectionName(User.class));
		cursor = collection.find();
		while (cursor.hasNext()) {
			System.out.println(cursor.next());
		}

		// drop collection
		operations.dropCollection(User.class);

		/**
		 * remove _filed class
		 */
		context = new ClassPathXmlApplicationContext("SpringConfig3.xml");
		operations = context.getBean("mongoTemplate", MongoOperations.class);

		// save
		user = new User("wss", "123456");
		operations.save(user);
		System.out.println("1. user: " + user);
		
		user = new User("wss", "123456");
		operations.save(user);

		collection = operations.getCollection(operations
				.getCollectionName(User.class));
		cursor = collection.find();
		while (cursor.hasNext()) {
			System.out.println(cursor.next());
		}

		// drop collection
		operations.dropCollection(User.class);

	}
}
